<template>
  <!-- 冷铁基础信息表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="900"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="115">
      <el-row>
        <el-col :span="9">
          <el-form-item label="名称" prop="name">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.name"
              placeholder="请输入名称"
              clearable
            />

            <span v-else>{{ formData.name }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="尺寸mm" prop="size">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.size"
              placeholder="请输入尺寸mm"
              clearable
            />

            <span v-else>{{ formData.size }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="9">
          <el-form-item label="重量/kg" prop="weight">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.weight"
              placeholder="请输入重量/kg"
              clearable
            />

            <span v-else>{{ formData.weight }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="安全库存" prop="safetyStock">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.safetyStock"
              placeholder="请输入安全库存"
              clearable
            />

            <span v-else>{{ formData.safetyStock }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="9">
          <el-form-item label="使用工序" prop="usageProcess">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.usageProcess"
              placeholder="请输入使用工序"
              clearable
            />

            <span v-else>{{ formData.usageProcess }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="装载数量+3%" prop="loadingQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.loadingQuantity"
              placeholder="请输入装载数量+3%"
              clearable
            />

            <span v-else>{{ formData.loadingQuantity }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="9">
          <el-form-item label="保质期/天" prop="qualityGuaranteePeriod">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.qualityGuaranteePeriod"
              placeholder="请输入保质期/天"
              clearable
            />

            <span v-else>{{ formData.qualityGuaranteePeriod }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="是否回收" prop="isRecycle">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.isRecycle"
              placeholder="请选择是否回收"
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('YesNo')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{ useDictionary("YesNo", formData.isRecycle) }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 照片 -->
    <el-form-item
      prop="imgUrl"
      style="position: absolute; top: 90px; right: 35px"
    >
      <upload-imge
        :action="`${actionUrl}/system/fileCenter/uploadFile/file`"
        v-model="formData.img"
        :domainName="`${actionUrl}`"
        :isReadonly="props.isReadonly"
      />
      <el-input v-model="formData.img" style="display: none" />
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESIRONBASEINFOADDORUPDATE",
  inheritAttrs: false,
});
// 图片地址
const actionUrl = import.meta.env.VITE_APP_BASE_API;
const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  name: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  size: [
    { required: true, message: "请输入尺寸mm", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50", trigger: "blur" },
  ],
  weight: [
    { required: true, message: "请输入重量", trigger: "blur" },
    {
      validator: planQuantityNew,
      trigger: "blur",
    },
  ],
  img: [{ min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }],
  safetyStock: [
    { required: true, message: "请输入安全库存", trigger: "blur" },
    { min: 1, max: 5, message: "长度在 1 到 5 ", trigger: "blur" },
    {
      validator: planQuantity,
      trigger: "blur",
    },
  ],
  usageProcess: [
    { required: true, message: "请输入使用工序", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  loadingQuantity: [
    { required: true, message: "请输入装载数量+3%", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  qualityGuaranteePeriod: [
    { required: true, message: "请输入保质期/天", trigger: "blur" },
    { min: 1, max: 5, message: "长度在 1 到 5", trigger: "blur" },
    {
      validator: planQuantity,
      trigger: "blur",
    },
  ],
  isRecycle: [{ required: true, message: "请选择是否回收", trigger: "blur" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  name: "",
  size: "",
  weight: "",
  img: "",
  safetyStock: "",
  usageProcess: "",
  loadingQuantity: "",
  qualityGuaranteePeriod: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  isRecycle: "1",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        name,
        size,
        weight,
        img,
        safetyStock,
        usageProcess,
        loadingQuantity,
        qualityGuaranteePeriod,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        isRecycle,
      } = newVal;
      Object.assign(formData, {
        id,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        name,
        size,
        weight,
        img,
        safetyStock,
        usageProcess,
        loadingQuantity,
        qualityGuaranteePeriod,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        isRecycle,
      });
      formData.weight = String(formData.weight);
      formData.safetyStock = String(formData.safetyStock);
      formData.isRecycle = String(formData.isRecycle);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.name = "";
  formData.size = "";
  formData.weight = "";
  formData.img = "";
  formData.safetyStock = "";
  formData.usageProcess = "";
  formData.loadingQuantity = "";
  formData.qualityGuaranteePeriod = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.isRecycle = "1";
}

const loading = ref(false);

/** 冷铁基础信息保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesironbaseinfo/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
function planQuantity(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else {
    callback();
  }
}
function planQuantityNew(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^(?!0(\.0+)?$)\d+(\.\d{1,6})?$/.test(value)) {
    callback(new Error("小数不能超过6位"));
  } else {
    callback();
  }
}
</script>
